package com.ft.oa.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ft.oa.domain.dto.sys.SecurityUser;
import com.ft.oa.domain.sys.SysOperateLog;
import com.ft.oa.mapper.sys.SysOperateLogMapper;
import com.ft.oa.service.sys.SysOperateLogService;
import com.ft.oa.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysOperateLogServiceImpl implements SysOperateLogService {

    @Resource
    private SysOperateLogMapper sysOperateLogMapper;


    @Override
    public Page<SysOperateLog> page(SysOperateLog condition) {

        QueryWrapper<SysOperateLog> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(StringUtils.hasText(condition.getModule()), SysOperateLog::getModule, condition.getModule())
                .like(StringUtils.hasText(condition.getInfo()), SysOperateLog::getInfo, condition.getInfo())
                .like(StringUtils.hasText(condition.getCreatorName()), SysOperateLog::getCreatorName, condition.getCreatorName())
                .ge(condition.getBeforeTime() != null, SysOperateLog::getCreateTime, condition.getBeforeTime())
                .le(condition.getAfterTime() != null, SysOperateLog::getCreateTime, condition.getAfterTime());

        Page<SysOperateLog> pageCondition = new Page<>(condition.getPage(), condition.getSize());
        Page<SysOperateLog> page = sysOperateLogMapper.selectPage(pageCondition, wrapper);

        return page;
    }

    @Override
    public List<String> moduleList() {
        QueryWrapper<SysOperateLog> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .select(SysOperateLog::getModule)
                .groupBy(SysOperateLog::getModule);
        List<Object> list = sysOperateLogMapper.selectObjs(wrapper);
        List<String> collect = list.stream().map(Object::toString).collect(Collectors.toList());
        return collect;
    }


    @Transactional
    @Override
    public void saveOperateLog(String info, String module, String type){
        SecurityUser currentUser = SecurityUtils.getCurrentUser();
        SysOperateLog log = SysOperateLog.builder()
                .info(info)
                .module(module)
                .type(type)
                .creator(currentUser.getId())
                .creatorName(currentUser.getUsername())
                .createTime(LocalDateTime.now())
                .build();
        int insert = sysOperateLogMapper.insert(log);

    }
}
